package com.tanhua.management.interceptor;

import com.tanhua.management.pojo.Manager;
import com.tanhua.management.service.SystemService;

import com.tanhua.management.utils.ManagerThreadLocal;
import com.tanhua.management.utils.NoAuthorization;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一完成根据token查询用User的功能
 */
@Component
public class TokenInterceptor01 implements HandlerInterceptor {

    @Autowired
    private SystemService systemService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            NoAuthorization noAnnotation = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
            if (noAnnotation != null) {
                // 如果该方法被标记为无需验证token，直接返回即可
                return true;
            }
        }

        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)) {
            //传入token和ip地址验证
            String xFor = request.getHeader("X-Forwarded-For");
            String[] split = xFor.split(",");
            String addr = split[0];
            Manager manager = this.systemService.queryMangerByToken(token, addr);
            if (null != manager) {
                ManagerThreadLocal.set(manager); //将当前对象，存储到当前的线程中
                return true;
            }
        }
        //请求头中如不存在Authorization直接返回false
        response.setStatus(401); //无权限访问
       // response.sendRedirect("http://192.168.24.48:8080");
        return false;
    }
}
